package com.chuangjiangx.member.stored.ddd.domain.subscribe;

import com.chuangjiangx.commons.JacksonUtils;
import com.chuangjiangx.member.basic.ddd.domain.service.MemberRedisDomainService;
import com.chuangjiangx.member.stored.ddd.domain.service.MbrConsumerService;
import com.chuangjiangx.member.stored.ddd.domain.service.MbrRechargeService;
import com.chuangjiangx.member.stored.ddd.domain.event.MbrPaySuccessEvent;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.Objects;

/**
 * @author cj-ch
 * @date 2018/5/23 下午3:54
 * 会员支付成功后事件监听
 */
@Slf4j
public class MbrPaySuccessListener {

    @Autowired
    protected ObjectMapper objectMapper;

    @Autowired
    protected MemberRedisDomainService memberRedisDomainService;

    @Autowired
    protected MbrRechargeService mbrRechargeService;
    @Autowired
    protected MbrConsumerService mbrConsumerService;


    public void handleMessage(Serializable message){
        if(null == message || StringUtils.isBlank(message.toString())){
            return;
        }
        MbrPaySuccessEvent event = convertMessage(message);

        /*
        前置条件检查
        1.过滤检测是否未开通会员中心
        2.如果是非会员卡消费,过滤不支持支付即会员功能的支付渠道
        3.查询数据库是否已经处理完成
         */
        if(!check(event)){
            return;
        }

        MbrPaySuccessEvent.Type serviceType = event.serviceType();
        if(Objects.equals(MbrPaySuccessEvent.Type.CONSUMER,serviceType)){
            //处理消费业务
            mbrConsumerService.service(event);
        } else {
            //处理充值业务
            mbrRechargeService.service(event);
        }

    }

    protected MbrPaySuccessEvent convertMessage(Serializable message) {
        return JacksonUtils.toObject(objectMapper, message.toString(), MbrPaySuccessEvent.class);
    }

    /**
     * 前置条件检查
     * @param event
     * @return
     */
    protected boolean check(MbrPaySuccessEvent event){
        if(null == event){
            return false;
        }
        //1.
        if(!memberRedisDomainService.merchantOpenedMember(event.getMerchantId())){
            //过滤未开通会员功能的商户
            return false;
        }
        return true;
    }


}
